package renguanyu.app.auth4fx.controller.permission;

import javafx.concurrent.Task;
import renguanyu.app.auth4fx.App;
import renguanyu.app.auth4fx.model.permission.PermissionDto;
import renguanyu.app.auth4fx.service.permission.PermissionService;
import renguanyu.app.auth4fx.view.permission.PermissionListView;

import java.util.List;
import java.util.stream.Collectors;

public class PermissionInfoDeleteController extends Task<Void> {

    private PermissionListView permissionListView;
    public PermissionInfoDeleteController(PermissionListView permissionListView) {
        this.permissionListView = permissionListView;
    }

    public void execute() {
        System.out.println("PermissionInfoDelete.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private Integer affectedRows = 0;
    @Override
    protected Void call() {
        System.out.println("PermissionInfoDelete.call");
        PermissionDto permissionDto = buildPermissionDto();
        affectedRows = PermissionService.deletePermission(permissionDto);
        return null;
    }

    private PermissionDto buildPermissionDto() {
        List<String> ids = permissionListView.selectedPermissionList.stream().map(
            permission -> permission.getId().toString()
        ).collect(Collectors.toList());
        PermissionDto permissionDto = new PermissionDto();
        permissionDto.setIds(ids);
        return permissionDto;
    }

    @Override
    protected void running() {
        System.out.println("PermissionInfoDelete.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("PermissionInfoDelete.succeeded");
        if(affectedRows >= 1){
            App.mainView.setCenter(new PermissionListView());
        }
    }

    @Override
    protected void failed() {
        System.out.println("PermissionInfoDelete.failed");
    }
}
